package com.pz.cloud.framework.model;

import com.baomidou.mybatisplus.annotation.TableName;
import com.pz.cloud.framework.base.model.Pageable;
import com.pz.cloud.framework.base.model.WorkflowEntity;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.BeanConvertUtil;

import javax.persistence.Table;
import java.util.Map;

/**
 * sql装饰类
 * @author 3hmzz
 */
public class SqlBuilder extends AbstractSqlBuilder{
    private SqlBuilder(){
        super();
    }
    private SqlBuilder(String initSql){
        super(initSql);
    }
    /**
     * 数据范围过滤
     * @param entity
     * @param alias
     * @return
     */
    public SqlBuilder authFilter(WorkflowEntity entity, String alias){
//        BizUtil.assembleAuthSql(this.sql,this.getParmMap(),alias,entity);
        return this;
    }

    public static SqlBuilder getInstance(){
        return new SqlBuilder();
    }

    public static SqlBuilder init(String sql){
        return new SqlBuilder(sql);
    }
    public static SqlBuilder select(String sql){
        return (SqlBuilder) new SqlBuilder().append("select ").append(sql);
    }
    public static <T>SqlBuilder init(T entity, String alias){
       return init(entity,alias, null);
    }
    public static <T>SqlBuilder init(T entity, String alias, Map parms){
        String tableName = null;

        Table table = entity.getClass().getAnnotation(Table.class);
        if(table!=null){
            tableName = table.name();
        }else{
            TableName t =  entity.getClass().getAnnotation(TableName.class);
            if(t!=null){
                tableName =  t.value();
            }else{
                tableName =  BeanConvertUtil.camelToUnderline(entity.getClass().getSimpleName());
            }
        }

        SqlBuilder sqlBuilder = (SqlBuilder) init("select * from ").append(tableName).append(" ").append(alias==null?"":alias).append(" where 1=1 ")
                .joinCondition(entity, alias,parms).returnType(entity.getClass());
        if(entity instanceof Pageable){
            sqlBuilder.page((Pageable) entity);
        }
        return sqlBuilder;
    }
}
